package com.smartaccounting.controller;

import com.smartaccounting.dao.UserDAO;
import com.smartaccounting.model.User;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    private UserDAO userDAO;

    @Override
    public void init() throws ServletException {
        userDAO = new UserDAO();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");
        String fullName = request.getParameter("fullName");
        String studentId = request.getParameter("studentId");

        try {
            // 检查用户名是否存在
            if (userDAO.isUsernameExists(username)) {
                request.setAttribute("error", "用户名已存在");
                request.getRequestDispatcher("register.jsp").forward(request, response);
                return;
            }

            // 检查邮箱是否存在
            if (userDAO.isEmailExists(email)) {
                request.setAttribute("error", "邮箱已被注册");
                request.getRequestDispatcher("register.jsp").forward(request, response);
                return;
            }

            // 创建新用户
            User user = new User(username, password, email, phone, fullName, studentId);
            if (userDAO.addUser(user)) {
                response.sendRedirect("login.jsp?register=success");
            } else {
                request.setAttribute("error", "注册失败，请重试");
                request.getRequestDispatcher("register.jsp").forward(request, response);
            }
        } catch (SQLException e) {
            throw new ServletException("数据库错误", e);
        }
    }
}